package com.example.demo2.controller;


import com.example.demo2.entity.User;
import com.example.demo2.service.UserService;
import com.google.gson.Gson;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController extends BaseController{

    @Autowired(required = false)
    private UserService userService;

    @GetMapping("/login")
    public String findByUserId(HttpSession session, @Param("userId") Integer userId, @Param("userPwd") String userPwd){
        userPwd = DigestUtils.md5DigestAsHex(userPwd.getBytes());
        User users = userService.findByUserId(userId,userPwd);
        Gson  gson = new Gson();
        session.setAttribute("uid",users.getUserId());
        return gson.toJson(users);
    }

    @RequestMapping("/register")
    public boolean insert_user(@Param("userId") Integer userId,
                               @Param("userName") String userName,
                               @Param("userPwd") String  userPwd,
                               @Param("userQuestion") String userQuestion)

    {
        userPwd = DigestUtils.md5DigestAsHex(userPwd.getBytes());
        return userService.insert_user(userId,userName,userPwd,userQuestion);
    }


    @GetMapping("/findByUserId_A")
    public String findByUserId_A(@Param("userId") Integer userId) {
        List<User> findByUserId_A = userService.findByUserId_A(userId);
        Gson gson = new Gson();
        return gson.toJson(findByUserId_A);
    }

    @RequestMapping("/upDateUserPwd")
    public boolean upDateUserPwd(@Param("userId") Integer userId,
                                 @Param("userPwd") String userPwd){
        userPwd =  DigestUtils.md5DigestAsHex(userPwd.getBytes());
        return userService.upDateUserPwd(userId,userPwd);
    }
    @RequestMapping("/upDateUserInformation")
    public boolean upDateUserInformation(@Param("userId") Integer userId,
                                         @Param("userName") String userName,
                                         @Param("userEmail") String userEmail,
                                         @Param("userBrief") String userBrief){
        return userService.upDateUserInformation(userId,userName,userEmail,userBrief);
    }
    @GetMapping("/forgetPwd")
    public String forgetPwd(@Param("userId") Integer userId,
                            @Param("userName") String userName,
                            @Param("userQuestion") String userQuestion){
        List<User> forgetPwd = userService.forgetPwd(userId,userName,userQuestion);
        Gson gson = new Gson();
        return gson.toJson(forgetPwd);

    }

}
